package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //通过httpclinet，构造登录凭证校验请求
        Map<String,String> parammap = new HashMap<>();
        parammap.put("appid", weChatProperties.getAppid());
        parammap.put("secret", weChatProperties.getSecret());
        parammap.put("js_code", userLoginDTO.getCode());
        parammap.put("grant_type", "authorization_code");
        String msg = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", parammap);
        //解析响应结果，获取openid
        JSONObject jsonObject = JSON.parseObject(msg);
        String openid = (String)jsonObject.get("openid");
        if (openid == null || openid.equals("")) {
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        //判断是否为新用户，根据openid查user表
        User user = userMapper.selectUserByOpenid(openid);
        //如果是新用户，初始化用户数据到user表
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insertUser(user);
        }
        //否则直接返回User对象
        return user;
    }
}
